package com.itheima.controller.system;

import com.itheima.controller.BaseServlet;
import com.itheima.domain.system.SystemSet;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.MD5Util;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * 实现用户注册，用户登录
 * 2021/10/15 15:09
 * created by guowenliang
 */
@WebServlet(urlPatterns = "/loginServlet")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 1.获取参数
        String method = request.getParameter("method");
        if ("login".equals(method)) {
            login(request, response);
        } else if ("register".equals(method)) {
            register(request, response);
        } else if ("returnRegister".equals(method)) {
            returnRegister(request, response);
        } else if ("logout".equals(method)) {
            logout(request, response);
        } else if ("getCode".equals(method)) {
            getCode(request, response);
        } else if ("toUploadPicture".equals(method)) {
            toUploadPicture(request, response);
        } else if ("UploadPicture".equals(method)) {
            UploadPicture(request, response);
        } else if ("toResetPassword".equals(method)){
            toResetPassword(request,response);
        } else if ("toReset".equals(method)){
            toReset(request,response);
        } else if ("forget".equals(method)){
            forget(request,response);
        } else if ("toForgetReset".equals(method)){
            toForgetReset(request,response);
        } else if ("toSystemSet".equals(method)){
            toSystemSet(request,response);
        } else if ("systemSet".equals(method)){
            systemSet(request,response);
        }
    }

    //忘记密码 重设界面
    private void toForgetReset(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应格式
        response.setContentType("text/html;charset=utf-8");
        //获取参数
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        //判断是否有空值0
        if (username.equals("")||email.equals("")||password.equals("")){

            String str="<font size=\"3\" color=\"red\">用户名不能为空，邮箱不能为空,新密码不能为空</font>";
            response.getWriter().write(str);
            response.setHeader("Refresh","5;URL=/loginServlet?method=forget");
        }else {
            //调用service
            UserService userService=new UserServiceImpl();
            User user = userService.findUserByNameAndEmail(username, email);
            //判断用户名和邮箱是否存在
            if (user.getUserName().equals(username)&&user.getEmail().equals(email)){
            userService.updatePasswordByNameAndEmail(username,email,password);
            request.getRequestDispatcher("/loginServlet?method=logout").forward(request,response);
            }

        }
    }

    // 保存
    private void systemSet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] moduleNames = request.getParameterValues("moduleName");
        for (String moduleName : moduleNames) {
            String moduleNamePageSize = request.getParameter(moduleName + "PageSize");
            userService.updatePageSize(moduleName,moduleNamePageSize);
        }
        // 返回设置界面
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(System.currentTimeMillis());
        request.setAttribute("msg","保存成功,时间："+time);
        toSystemSet(request,response);
    }

    // 通过模块名称查询设置的页面页数
    private String findSystemSetByModuleName(String moduleName){
        SystemSet systemSet = userService.findSystemSetByModuleName(moduleName);
        String pageSize = systemSet.getPageSize();
        return pageSize;
    }

    // 跳转到设置界面
    private void toSystemSet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<SystemSet> systemSetList= userService.findSystemSet();
        request.setAttribute("systemSetList",systemSetList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/systemSet.jsp").forward(request, response);
    }

    //跳转忘记密码界面
    private void forget(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(request.getContextPath()+"/WEB-INF/pages/system/user/forgetPassword.jsp").forward(request,response);
    }

    //修改密码
    private void toReset(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应格式
        response.setContentType("text/html;charset=utf-8");
        //获取参数
        String oldpassword = request.getParameter("oldpassword");
        String newpassword = request.getParameter("newpassword");
        String ispassword = request.getParameter("ispassword");

        if (oldpassword.equals("")||newpassword.equals("")||ispassword.equals("")){
            String str="<font size=\"3\" color=\"red\">新旧密码不能为空</font>";
            response.getWriter().write(str);
            response.setHeader("Refresh","5;URL=/loginServlet?method=toResetPassword");
        }else{
            //获取用户名
            Cookie[] cookies = request.getCookies();
            Cookie cookie=cookies[0];
            String username = cookie.getValue();
            //加密页面获取旧密码
            String opassword= MD5Util.md5(oldpassword);
            //调用方法
            UserService userService=new UserServiceImpl();
            User user = userService.findUserAndPassword(username, opassword);
            //判断密码是否正确，判断新密码与第二次输入是否一致
            if (user.getPassword().equals(opassword)){
                if (newpassword.equals(ispassword)){
                    //修改密码
                    userService.updatePassword(username, newpassword);
                    //退出登录状态
                    request.getRequestDispatcher("/loginServlet?method=logout").forward(request,response);
                }
            }
        }
    }

    // 转发到修改密码界面
    private void toResetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(request.getContextPath()+"/WEB-INF/pages/system/user/resetPassword.jsp").forward(request,response);
    }
    private User findUserByUsername(HttpServletRequest request, HttpServletResponse response){
        String userName = request.getSession().getAttribute("username").toString();
        User user = userService.findUserByUsername(userName);
        return user;
    }

    // 上传头像
    private void UploadPicture(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(df);
        User user = userService.findUserByUsername(request.getSession().getAttribute("username").toString());
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (!fileItem.isFormField()) {
                    // 上传的图片
                    String path = this.getServletContext().getRealPath("fileupload");
                    String name = UUID.randomUUID().toString();
                    String suffix = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                    user.setPicture("/fileupload/" + name + suffix);
                    fileItem.write(new File(path, name + suffix));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.UploadPicture(user);
        request.setAttribute("user",user);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/home/main.jsp").forward(request, response);
    }

    private void toUploadPicture(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/uploadPicture.jsp").forward(request, response);
    }

    // 生成验证码
    private void getCode(HttpServletRequest request, HttpServletResponse response) {
        String phone = request.getParameter("phone");
        String code = userService.getCode(phone);
        // 数据处理
        request.getSession().setAttribute("code", code);
    }

    // 退出登录
    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 清除session
        request.getSession().setAttribute("username", null);
        // 清除自动登录
        Cookie cookie3 = new Cookie("autoLogin", null);
        cookie3.setMaxAge(0);
        response.addCookie(cookie3);
        // 相应数据
        request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
    }

    // 返回注册界面
    private void returnRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/home/register.jsp").forward(request, response);
    }

    // 注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        // 验证码正确
        if (code.equals(request.getSession().getAttribute("code"))) {
            User user = new User();
            user.setUserName(username);
            user.setPassword(password);
            user.setEmail(email);
            // 调用服务层
            userService.register(user);
            // 响应数据
            request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
        } else {
            String msg = "验证码输入错误";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher(request.getContextPath() + "/loginServlet?method=returnRegister").forward(request, response);
        }

    }

    // 登录
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        String autoLogin = request.getParameter("autoLogin");
        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        // 2.调用服务层
        boolean result = userService.findUser(user);

        // 3.处理结果
        if (result) {
            // 登录成功
            // 记住密码
            remember(response, username, password, remember, autoLogin);
            // 自动登录
            autoLogin(response, autoLogin);
            // 用session存储登录的username
            request.getSession().setAttribute("username", username);
            user = userService.findUserByUsername(username);
            request.getSession().setAttribute("user", user);
            request.setAttribute("user",user);
//            request.getSession().setAttribute("userPicture", user.getPicture());
            request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/home/main.jsp").forward(request, response);
        } else {
            // 4.响应数据
            // 登录失败
            String msg = "用户名或者密码错误";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
        }
    }

    // 自动登录
    private void autoLogin(HttpServletResponse response, String autoLogin) {
        if ("yes".equals(autoLogin)) {
            Cookie cookie3 = new Cookie("autoLogin", autoLogin);
            cookie3.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie3);
        } else {
            Cookie cookie3 = new Cookie("autoLogin", autoLogin);
            cookie3.setMaxAge(0);
            response.addCookie(cookie3);
        }
    }

    // 记住密码
    private void remember(HttpServletResponse response, String username, String password, String remember, String autoLogin) {
        if ("yes".equals(remember)) {
            Cookie cookie1 = new Cookie("username", username);
            Cookie cookie2 = new Cookie("password", password);
            // 密码存储七天
            cookie1.setMaxAge(60 * 60 * 24 * 7);
            cookie2.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        } else {
            Cookie cookie1 = new Cookie("username", username);
            Cookie cookie2 = new Cookie("password", password);
            // 清楚cookie
            cookie1.setMaxAge(0);
            cookie2.setMaxAge(0);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }
    }
}